<?php
/**
 * Created by PhpStorm.
 * User: PEMEO
 * Date: 10/8/2014
 * Time: 10:09 PM
 */
namespace Frontend\Modules\Video\Controllers;
use Phalcon\Paginator\Adapter\QueryBuilder;
use Phalcon\Mvc\Model\Resultset;
use Library\Pagination\Pager as Pager;
use Phalcon\Mvc\User\Component;
use Common\Models\Videos\VideoCategory;
use Common\Models\Videos\National;
use Common\Models\Videos\Artist;
use Common\Library\Common as LibraryCommon;
use Common\Models\Videos\Video;
use Common\Models\Videos\VideoCategoryLink;
use Library\Constant\Constant;
use Phalcon\Mvc\View;
use Phalcon\Http\Response;
class SearchController extends  \FrontendController
{
    public  function indexAction($params){
        try {
            if($params=='phim' || $params=='tvshow' || $params=='clip'){
                $urlSearch = 'video/search/'.$params.'?key=';
                $key = $this->request->getQuery('key','string');
                if($key!='') {
                    $this->assets
                        ->addCss('vendor/frontend/css/video/search/search.css')
                        ->addCss('vendor/frontend/css/video/category/category.css')
                        ->addCss('vendor/frontend/css/home/home.css')
                        ->addJs('vendor/frontend/js/video/category/category_angular.js');
                    $limit = 10;
                    $currentPage = abs($this->request->getQuery('page', 'int', 1));
                    if ($currentPage == 0) {
                        $currentPage = 1;
                    }
                    $sqlWhere = 'video_description.name LIKE :name: OR artist.name LIKE :name:';
                    $conditionsWhere['name'] = '%' . $key . '%';
                    $sqlWhere = 'AND video.status = :status:';
                    $conditionsWhere['status'] = 'A';
                    
                    $builderSearch = $this->modelsManager->createBuilder()
                        ->from(array('video' => 'Common\Models\Videos\Video'))
                        ->groupBy('video.id')
                        ->join('Common\Models\Videos\VideoDescription', 'video.id = video_description.video_id','video_description')
                        ->join('Common\Models\Videos\VideoArtistLink', 'video.id = artist_link.video_id','artist_link')
                        ->join('Common\Models\Videos\Artist', 'artist.id = artist_link.artist_id','artist')
                        ->where($sqlWhere , $conditionsWhere)
                        ->orderBy('video.created_time');

                    $videos = new Pager(
                        new QueryBuilder(array(
                            'builder' => $builderSearch,
                            'limit' => $limit,
                            'page' => $currentPage,
                        )),
                        array(
                            // We will use Bootstrap framework styles
                            'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                            // Range window will be 5 pages
                            'rangeLength' => 5,
                            // Just a string with URL mask
                            'urlMask' => $this->getFrontendUrl() . $urlSearch . '&page={%page_number}',
                        )
                    );
                    $this->view->setVars(array(
                        'param'  => $params,
                        'videos' => $videos,
                        'num' => count($videos),
                        'key' => $key
                    ));
                    $this->view->render("video" , "search/index");
                }else{
                    return $this->response->redirect('/');
                }
            }else{
                //return $this->response->redirect('/');
            }



        }catch (\Exception $e) {
            $this->flash->error($e->getMessage());
        }
    }

    public function searchAction()
    {
        $key = $this->request->getQuery('name','string');
        $currentPage = abs($this->request->getQuery('p', 'int', 1));
        if ($currentPage == 0) {
            $currentPage = 1;
        }
        $uri = str_replace('&p=' . $currentPage , '' , $this->request->getURI());
        $keySearch = $this->constant->keyCache['video']['listVideoBySearchKey'] . '-' . $key . '-page-' . $currentPage;
        $videos = $this->modelsCache->get($keySearch);
        if(!$videos){
            $video = new Video();
            $conditions = $this->request->get();
            $conditions['status'] = 'A';
            $builderVideo = $video->queryBuilderSeachVideo($conditions);
            $videos = new Pager(
                new QueryBuilder(array(
                    "builder" => $builderVideo,
                    "limit"=> Constant::ITEM_PER_PAGE_20,
                    "page" => $currentPage
                )),
                array(
                    'layoutClass' => 'Library\Pagination\Pager\Layout\Bootstrap',
                    'rangeLength' => 5,
                    'urlMask'     => $uri . '&p={%page_number}',
                )
            );
            $this->modelsCache->save($keySearch , $pager , 7200);
        }

        $this->view->setVars(array(
            'videos' => $videos ,
            'key'   => $key
        ));
        $this->view->render("video" , "search/index");
    }

    public function  getListVideosByKey($sqlWhere,$conditionsWhere){

        return $this->modelsManager->createBuilder()
            ->from(array('video' => 'Common\Models\Videos\Video'))
            ->groupBy('video.id')
            ->join('Common\Models\Videos\VideoDescription', 'video.id = video_description.video_id','video_description')
            ->join('Common\Models\Videos\VideoArtistLink', 'video.id = artist_link.video_id','artist_link')
            ->join('Common\Models\Videos\Artist', 'artist.id = artist_link.artist_id','artist')
            ->where($sqlWhere , $conditionsWhere)
            ->orderBy('video.created_time')
            ->getQuery()
            ->execute();

    }
}